#include "groupchatswidget.h"
#include "sendmsg.h"
#include "ui_groupchatswidget.h"
#include <QMessageBox>
#include <QThread>
#include <QJsonDocument>
#include <QJsonObject>

GroupChatsWidget::GroupChatsWidget(QString name, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::GroupChatsWidget)
{
    ui->setupUi(this);
    this->name = name;

    ui->SendBtn->setDisabled(true);

    setWindowTitle("群聊");
    ui->MsgRecord->setReadOnly(true);

    // 创建线程对象
    QThread* sub = new QThread;
    // 创建任务对象
    SendMsg* worker = new SendMsg;
    // 将任务对象移动到子线程工作
    worker->moveToThread(sub);

    // 连接服务器信号处理
    connect(this, &GroupChatsWidget::ConnectServer, worker, &SendMsg::ConnectServer);

    // 重新连接信号处理
    connect(this, &GroupChatsWidget::ReconnectServer, worker, &SendMsg::ReconnectServer);

    // 连接成功信号处理
    connect(worker, &SendMsg::ConnectSuccessful, this, [=](){
        ui->SendBtn->setDisabled(false);
        ui->MsgRecord->append("\n提示：您已连接到服务器\n");
    });

    // 连接失败信号处理
    connect(worker, &SendMsg::ConnectFail, this, [=](){
        ui->MsgRecord->append("\n提示：未连接到服务器\n");
        QMessageBox::critical(this, "连接错误", "未连接到服务器");
        int res = QMessageBox::question(this, "提示", "是否重新连接", QMessageBox::Yes | QMessageBox::No);
        if(res == QMessageBox::Yes) {
            emit ReconnectServer();
        } else if(res == QMessageBox::No) {

        } else {

        }
    });

    // 断开连接信号处理
    connect(worker, &SendMsg::ConnectOver, this, [=](){
        ui->SendBtn->setDisabled(true);
        ui->MsgRecord->append("\n提示：您已断开服务器\n");
        sub->quit();
        sub->wait();
        worker->deleteLater();
        sub->deleteLater();
    });

    // 接收信息信号处理
    connect(worker, &SendMsg::ReceiveMessage, this, [=](QByteArray msg){
        QJsonDocument doc = QJsonDocument::fromJson(msg);
        QJsonObject obj = doc.object();
        ui->MsgRecord->append(obj["sender"].toString() + "：" + obj["message"].toString());
    });

    // 发出信息信号处理
    connect(this, &GroupChatsWidget::SendMessage, worker, &SendMsg::SendMessage);

    sub->start();
    // 发送连接服务器信号
    emit ConnectServer("39.104.13.102", 10000);

}

GroupChatsWidget::~GroupChatsWidget()
{
    delete ui;
}

void GroupChatsWidget::on_SendBtn_clicked()
{
    QJsonDocument doc;
    QJsonObject obj;
    obj["sender"] = name;
    obj["message"] = ui->MsgEdit->text();
    doc.setObject(obj);
    emit SendMessage(doc);
    ui->MsgRecord->append(name + "：" + ui->MsgEdit->text());
    ui->MsgEdit->clear();
}
